import React, { Component } from 'react'
import {
    Card,
    Button,
    Table,
    Modal,
    Form,
    message,
    Select,
    Input,
} from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import md5 from 'js-md5'

import LinkButton from '../../components/link-button'
import {reqUsers, reqAddOrUpdateUser, reqDeleteUser} from '../../api'
import {formatDateWithoutT} from '../../utils/dateUtils'
import errorMessage from '../../utils/messageUtils'

const {Item} = Form
const {Option} = Select
// 用户路由
export default class User extends Component {

    constructor (props) {
        super(props)
        // 获取form数据
        this.formRef = React.createRef()
        this.state = {
            showModal: false,
            users: [], // 用户列表
            roles: [], // 角色列表
            loadFlg: false,
            isUpdate: false,
            buttonDisabled: true,
            pageName: "用户管理",
        }
    }

    

    // 初始化列信息
    initColumns = () => {
        this.columns = [
            {
                title: '用户名',
                dataIndex: 'username',
            },
            {
                title: '邮箱',
                dataIndex: 'email',
            },
            {
                title: '联系方式',
                dataIndex: 'phone',
            },
            {
                title: '注册时间',
                dataIndex: 'createTime',
                render: createTime => formatDateWithoutT(createTime)
            },
            {
                title: '权限',
                dataIndex: 'roleId',
                render: (roleId) => this.roleNames[roleId]
            },
            {
                title: '操作',
                render: (user) => {
                    return (
                        <span>
                            <LinkButton onClick={() => this.updateStateSet(user)}>修改</LinkButton>
                            <LinkButton onClick={() => this.deleteOnClick(user)}>删除</LinkButton>
                        </span>
                    )
                }
            }
        ]
    }

    // 获取权限名
    initRoleNames = (roles) => {
        const roleNames = roles.reduce((pre, role) => {
            // bj["nam"] ，与 obj.nam 是一个意思，都是取 obj 对象的 nam 属性值
            pre[role.id] = role.roleName
            return pre
        }, {})
        // 保存
        this.roleNames = roleNames
    }

    // 设置更新状态
    updateStateSet = (user) => {
        this.user = user
        this.setState({isUpdate: true, showModal: true})
        const {username, password, phone, email, roleId} = user
        if (this.formRef.current) {
            this.formRef.current.setFieldsValue({username, password, phone, email, role:roleId})
        }
    }

    // 设置添加状态
    addStateSet = () => {
        this.user = null
        this.setState(({showModal: true, isUpdate: false}))
        if (this.formRef.current) {
            this.formRef.current.setFieldsValue({username:'', password:'', phone:'',email:'', role:''})
        }
    }

    // 获取用户数据
    getUsers = async () => {
        const reponse = await reqUsers()
        const result = reponse.data
        if (result.status === 0) {
            const {users, roles} = result.data
            this.initRoleNames(roles)
            this.setState({
                users, roles, buttonDisabled: false,
            })
        } else if (result.status === 2) {
            message.error("您没有使用" + this.state.pageName + "的权限")
        } else {
            message.error('获取用户信息失败')
        }
    }

    // 更新或添加用户
    addOrUpdateUser = async () => {
        // 表单验证，通过了才继续
        await this.formRef.current.validateFields()
        // 收集数据
        const {username, password, phone, email, role} = this.formRef.current.getFieldsValue()
        const user = {username, password: md5(password), phone, email, roleId: role}
        // 判断是否更新
        if (this.user) {
            user.id = this.user.id
        }
        const reponse = await reqAddOrUpdateUser(user)
        const result = reponse.data

        if (result.status === 0) {
            message.success(`${this.user ? '修改' : '添加'}用户信息成功`)
            this.setState({showModal: false, loadFlg: true})
            this.getUsers()
            this.setState({loadFlg: false})
        } else {
            errorMessage(result.message)
        }
    }

    // 删除用户
    deleteUser = async (userId) => {
        const reponse = await reqDeleteUser(userId)
        const result = reponse.data
        if (result.status === 0) {
            message.success('删除用户成功')
            this.setState({loadFlg: true})
            this.getUsers()
            this.setState({loadFlg: false})
        } else {
            message.error('删除用户失败')
        }
    }

    // 按删除按钮的回调
    deleteOnClick = (user) => {
        Modal.confirm({
            icon: <ExclamationCircleOutlined/>,
            content: `确认删除用户${user.username}吗？`,
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                this.deleteUser(user.id)
            }
        })
    }

    componentWillMount () {
        this.initColumns()
    }

    componentDidMount () {
        this.getUsers()
    }

    render() {
        const user = this.user || {}
        const {showModal, users, roles, loadFlg, isUpdate, buttonDisabled} = this.state
        const title = (
            <Button type="primary" onClick={this.addStateSet} disabled={buttonDisabled}>创建用户</Button>
        )
        return (
            <Card title={title}>
                <Table
                    bordered
                    rowKey='id'
                    dataSource={users}
                    loading={loadFlg}
                    columns={this.columns}
                    pagination={{defaultPageSize: '8', showQuickJumper: true}}
                />

                {/* 创建/修改 用户信息 */}
                <Modal title={isUpdate ? '修改用户' : '添加用户'}
                    visible={showModal}
                    onOk={this.addOrUpdateUser}
                    onCancel={() => this.setState({showModal: false})}
                    cancelText={'取消'}
                    okText={'确认'}>
                    <Form ref={this.formRef}>
                        <Item label="用户名" name='username'  labelCol={{span: 4}} wrapperCol={{span: 16}} 
                        rules={[{required: true, message: '用户名不能为空!'}]} initialValue={user.username}>
                            <Input placeholder={'请输入用户名'} allowClear={true}></Input>
                        </Item>
                        <Item label="密码" name='password'  labelCol={{span: 4}} wrapperCol={{span: 16}} 
                        rules={[{required: true, message: '密码不能为空!'}]} initialValue={user.password}>
                            <Input placeholder={'请输入密码'} type='password' allowClear={true}></Input>
                        </Item>
                        <Item label="联系方式" name='phone' labelCol={{span: 4}} wrapperCol={{span: 16}} initialValue={user.phone}>
                            <Input placeholder={'请输入联系方式'} allowClear={true}></Input>
                        </Item>
                        <Item label="邮箱" name='email'  labelCol={{span: 4}} wrapperCol={{span: 16}} initialValue={user.email}>
                            <Input placeholder={'请输入邮箱'} allowClear={true}></Input>
                        </Item>
                        <Item label="权限" name='role' labelCol={{span: 4}} wrapperCol={{span: 12}} rules={[
                            {required: true, message: '请为用户设置一个权限'}]} initialValue={user.roleId}>
                            <Select placeholder={'请选择用户权限'}>
                                {
                                    roles.map(
                                        item => {
                                            return (<Option key={item.id} value={item.id}>{item.roleName}</Option>)
                                        }
                                    )
                                }   
                            </Select>
                        </Item>
                    </Form>
                </Modal>
            </Card>
        )
    }
}
